package com.hanfu.ucenter.web.web.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * 银联支付 签名类
 * @author maxjcs
 *
 */
public class SignUtil {

	private static final Logger logger = LoggerFactory.getLogger(SignUtil.class);
	
	/**
	 * 获取签名
	 * @param map
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static String sign(String keysalt,Map map){
		try{
			//按key 排序
			Map sortMap=MapUtils.sortMapByKey(map);
			Set keySet=sortMap.keySet();
			Iterator it=keySet.iterator();
			String str="";
			while(it.hasNext()){
				String keystr=(String)it.next();
				Object value =sortMap.get(keystr);
				if(value instanceof  Boolean){
					if((Boolean)value){
						str+=keystr+"=true&";
					}else{
						str+=keystr+"=false&";
					}
				}else if(value instanceof java.util.List){
				    String valStr=GsonUtil.obj2Json(value);
					str+=keystr+"="+valStr+"&";
				}else{
                    str+=keystr+"="+value+"&";
                }
			}
			str=str.substring(0, str.length()-1)+keysalt;
			return MD5Util.md5(str).toUpperCase();
		}catch(Exception ex){
			logger.error("签名错误",ex);
		}
		return "";
	}
	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static void main(String[] args) {
		Map map=new HashMap();
		map.put("abc", "111");
		map.put("bcd", "222");
		map.put("abd","444" );
		
//		String a=SignUtil.sign("fcAmtnx7MwismjWNhNKdHC44mNXtnEQeJkRrhKJwyrW2ysRR",map);
//		System.out.println(a);
		
//		String aa="attachedData={merBillNo:2015090700000000}&billFunds=COUPON:200|PCARD:800&billFundsDesc=优惠金额2.00元，银行卡支付金额8.00元&buyerUsername=张三&invoiceAmount=800&merOrderId=2015090700000000&payTime=2015-09-07 16:00:00&status=SUCCESS&targetOrderId=2015090700000000&totalAmount=1000AAABBBCCCDDDEEEFFFGGG";
		String ab="billDate=2017-06-26&billNo=31940000201700002&goods=[{\"body\":\"微信二维码测试\",\"price\":\"1\",\"goodsName\":\"微信二维码测试\",\"goodsId\":\"1\",\"quantity\":\"1\",\"goodsCategory\":\"TEST\"}]&instMid=QRPAYDEFAULT&mid=898340149000005&msgSrc=WWW.TEST.COM&msgType=bills.getQRCode&requestTimestamp=2017-06-26 17:28:02&tid=88880001&totalAmount=1&walletOption=SINGLEfcAmtnx7MwismjWNhNKdHC44mNXtnEQeJkRrhKJwyrW2ysRR";
        System.out.println(DigestUtils.md5DigestAsHex(ab.getBytes()).toUpperCase());
		try {
			System.out.println(MD5Util.md5(ab).toUpperCase());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

}
